package service;

import common.Message;
import common.MessageType;
import utils.PrintUtil;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

/**
 * @author 余一
 * @date 2021/11/1  17:29
 * 服务端向所有客户端推送新闻
 */
public class NewsServiceThread implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("请输入服务端要推送的消息内容(exit表示退出推送消息的服务线程)：");
            String news = PrintUtil.readString(100);
            if ("exit".equals(news)){
                System.out.println("推送消息的服务线程退出");
                break;
            }
            Message message = new Message();
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
            LocalDateTime now = LocalDateTime.now();
            String nowDate = timeFormatter.format(now);
            message.setSendTime(nowDate);
            message.setMesType(MessageType.MESSAGE_TO_ALL);
            message.setSender("服务端");
            message.setContent(news);

            HashMap<String, ServerClientThread> threadHashMap = ThreadManager.getThreadHashMap();
            threadHashMap.forEach((userId,serverClientThread) -> {
                try {
                    OutputStream outputStream = serverClientThread.getSocket().getOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            System.out.println(message.getSender() + "向所有客户端推送一条消息："+ message.getContent());
        }
    }
}
